package com.jrx.anytxn.reporting.job.lsSecondFile.config;

import com.jrx.anytxn.common.exception.TxnException;
import com.jrx.anytxn.common.exception.TxnRuntimeException;
import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.param.dto.system.SystemParameterRes;
import com.jrx.anytxn.param.entity.BtBatchStatus;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.mapper.ext.ExtBtBatchStatusMapper;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.param.service.system.ISystemParameterService;
import com.jrx.anytxn.reporting.config.AnyTxnBatchProperties;
import com.jrx.anytxn.reporting.constant.ReportingConstant;
import com.jrx.anytxn.reporting.job.lsSecondFile.step.LSSecondContractFileListener;
import com.jrx.anytxn.reporting.job.lsSecondFile.step.LSSecondContractFileProcessor;
import com.jrx.anytxn.reporting.job.lsSecondFile.step.LSSecondContractFileReader;
import com.jrx.anytxn.reporting.job.lsSecondFile.step.LSSecondContractFileWriter;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.item.ItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.SimpleAsyncTaskExecutor;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 生成第二代征信个人合同信息(增量抽取)
 *
 * @author liuyang
 * @date 2021-04-26
 */
@Configuration
@EnableConfigurationProperties(AnyTxnBatchProperties.class)
@EnableBatchProcessing
public class GenerateLSSecondContractFileConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(GenerateLSSecondContractFileConfiguration.class);

    @Resource(name = "bizSqlSessionFactory")
    SqlSessionFactory sqlSessionFactory;
    @Autowired
    public JobBuilderFactory jobBuilderFactory;
    @Autowired
    public StepBuilderFactory stepBuilderFactory;
    @Autowired
    private AnyTxnBatchProperties anyTxnBatchProperties;
    @Autowired
    private IOrganizationTableService organizationTableService;
    @Autowired
    private LSSecondContractFileListener contractFileListener;
    @Autowired
    private LSSecondContractFileProcessor contractFileProcessor;
    @Autowired
    private LSSecondContractFileWriter contractFileWriter;
    @Resource
    private ExtBtBatchStatusMapper extBtBatchStatusMapper;
    @Autowired
    private ISystemParameterService systemParameterService;

    @Bean
    public Job generateLSSecondContractFileJob() {
        return jobBuilderFactory.get("generateLSSecondContractFileJob").incrementer(new RunIdIncrementer()).listener(contractFileListener)
                .start(generateLSSecondContractFileStep())
                .build();
    }

    @Bean
    public Step generateLSSecondContractFileStep() {
        return stepBuilderFactory.get("generateLSSecondContractFileStep")
                .<String, String>chunk(anyTxnBatchProperties.getFileConfig().getChunkLimit())
                .reader(secondContractLSFileReader())
                .processor(contractFileProcessor)
                .writer(contractFileWriter)
                .taskExecutor(new SimpleAsyncTaskExecutor())
                .throttleLimit(anyTxnBatchProperties.getFileConfig().getThrottleLimit())
                .build();
    }

    @Bean
    @StepScope
    public ItemReader<String> secondContractLSFileReader() {
        logger.info("生成临商第二代征信贷款合同信息文件批量启动,读取正常的账户信息，机构：{}", ReportingConstant.DEFAULT_ORG_NUMBER);
        PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(ReportingConstant.DEFAULT_ORG_NUMBER);
        BtBatchStatus batchStatus = extBtBatchStatusMapper.selectByStatusAndJobName(ReportingConstant.BATCH_SATTUS_2, ReportingConstant.CUTOVER_END,
                org.getTenantId(), org.getToday());
        Date startTime = null;
        if (null != batchStatus) {
            startTime = batchStatus.getCreateTime();
        }
        try {
            // 判断是不是全量抽取日期，如果是则设置startTime=null，进行全量抽取。
            SystemParameterRes systemParameterRes = systemParameterService.findByParamCode(ReportingConstant.REPORTING_ALL_DATE, org.getTenantId());
            String reportingAllDate = systemParameterRes!=null ? systemParameterRes.getParamValue() : "";
            String todayStr = DateUtils.format(org.getToday(), DateUtils.DATE_PATTERN);
            if (todayStr.equals(reportingAllDate)){
                startTime = null;
            }
        } catch (TxnException e) {
            logger.error("获取全量抽取日期异常：{}", e);
            throw new TxnRuntimeException(e.getErrCode(), e.getErrMsg());
        }
        return new LSSecondContractFileReader(sqlSessionFactory, anyTxnBatchProperties.getFileConfig().getPageSize(), startTime);
    }
}
